package service4admin

import (
	"Gin-Gorm-boke/boke_admin/models4admin"
	"Gin-Gorm-boke/boke_common/models"
	"Gin-Gorm-boke/boke_common/response"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"strconv"
)

type TagVo struct {
	Id     int    `json:"id"`
	Name   string `json:"name"`
	Remark string `json:"remark"`
}

func GetTagList(c *gin.Context) {
	pageNum, _ := strconv.Atoi(c.DefaultQuery("pageNum", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "10"))
	name := c.Query("name")
	remark := c.Query("remark")
	db := models.Db.Model(new(models4admin.Tag))
	if name != "" {
		db.Where("name like ?", "%"+name+"%")
	}
	if remark != "" {
		db.Where("remark like ?", "%"+remark+"%")
	}
	var total int64
	db.Count(&total)
	var tagList []models4admin.Tag
	var tagVoList []TagVo
	db.Offset((pageNum - 1) * pageSize).Limit(pageSize).Find(&tagList)
	copier.Copy(&tagVoList, &tagList)
	response.ResponseOK(c, gin.H{
		"total": total,
		"rows":  tagVoList,
	})
	return
}
func SaveTag(c *gin.Context) {
	var tag models4admin.Tag
	if err := c.ShouldBindJSON(&tag); err != nil {
		response.ResponseBadRequest(c)
		return
	}
	models.Db.Create(&tag)
	response.ResponseOK(c, nil)

}

func DelTag(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	models.Db.Delete(&models4admin.Tag{}, id)
	response.ResponseOK(c, nil)
	return
}

func UpdateTag(c *gin.Context) {
	var tag models4admin.Tag
	if err := c.ShouldBindJSON(&tag); err != nil {
		response.ResponseBadRequest(c)
		return
	}
	models.Db.Model(new(models4admin.Tag)).Where("id=?", tag.Id).Updates(&tag)
	response.ResponseOK(c, nil)
	return
}

func GetTagById(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	var tag models4admin.Tag
	models.Db.Where("id=?", id).First(&tag)
	response.ResponseOK(c, tag)
	return
}

func ListAllTag(c *gin.Context) {
	var tagList []models4admin.Tag
	models.Db.Find(&tagList)
	response.ResponseOK(c, tagList)
	return
}
